package com.talkyun.openx.interceptor.repeat;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.talkyun.openx.server.core.ServiceContext;
import com.talkyun.openx.server.core.ServiceRequest;
import com.talkyun.utils.MD5;
import com.talkyun.utils.json.JSON;

import java.util.concurrent.TimeUnit;

public class RepeatManager {
    private Object obj = new Object();
    private Cache<String, Object> cache;

    public RepeatManager(int interval) {
        this.updateInterval(interval);
    }

    public synchronized void updateInterval(int interval) {
        if (interval < 10) {
            throw new RuntimeException("Interval is too small! " + interval);
        }
        if (cache != null) {
            cache.cleanUp();
        }

        cache = CacheBuilder.newBuilder().maximumSize(32 * 1024).expireAfterWrite(interval, TimeUnit.MILLISECONDS).build();
    }

    public boolean isRepeat(ServiceRequest sr) {
        try {
            return doIsRepeat(sr);
        } catch (Throwable t) {
            return false;
        }
    }

    private boolean doIsRepeat(ServiceRequest sr) {
        String md5 = getMd5(sr);
        Object item = cache.getIfPresent(md5);

        if (item != null) {
            return true;
        } else {
            cache.put(md5, obj);
        }
        return false;
    }


    private String getMd5(ServiceRequest sr) {
        // ip + session + body => md5
        ServiceContext ctx = ServiceContext.get();
        StringBuilder sb = new StringBuilder(64);
        String ip = ctx.getString(ServiceContext.REQ_IP, ".");
        String session = sr.getSession();
        String body = JSON.toJsonString(sr);
        sb.append(ip).append("$").append(session).append("$").append(body);
        return MD5.md5(sb.toString());
    }

}